package com.muzi.onvif.util;

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.digest.MessageDigestAlgorithms;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.text.SimpleDateFormat;
import java.util.*;

public class PasswordUtils {
    private static Random rnd = new SecureRandom();
    public static String nonce =  "";
    public static String utcTime = "";

    public static String encryptPassword(String password) {
        nonce =  "" + rnd.nextInt();
        String timestamp = getUTCTime();
        String beforeEncryption = nonce + timestamp + password;
        byte[] encryptedRaw;
        try {
            encryptedRaw = sha1(beforeEncryption);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            return null;
        }
        String encoded = Base64.encodeBase64String(encryptedRaw);
        return encoded;
    }

    // Other required methods on interface need no guts
    private static byte[] sha1(String s) throws NoSuchAlgorithmException {
        MessageDigest SHA1 = MessageDigest.getInstance(MessageDigestAlgorithms.SHA_1);
        SHA1.reset();
        SHA1.update(s.getBytes());
        return SHA1.digest();
    }
    public static String getUTCTime() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-d'T'HH:mm:ss'Z'");
        sdf.setTimeZone(new SimpleTimeZone(SimpleTimeZone.UTC_TIME, "UTC"));
        Calendar cal = new GregorianCalendar(TimeZone.getTimeZone("UTC"));
        String utcTime = sdf.format(cal.getTime());
        PasswordUtils.utcTime = utcTime;
        return utcTime;
    }
}
